<?php
/***************************************************************
 *  Copyright notice
 *
 *  (c) 2011 Gerhard Kollinger <gerhard@kollinger.it>
 *  All rights reserved
 *
 *  This script is part of the TYPO3 project. The TYPO3 project is
 *  free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  The GNU General Public License can be found at
 *  http://www.gnu.org/copyleft/gpl.html.
 *
 *  This script is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  This copyright notice MUST APPEAR in all copies of the script!
 ***************************************************************/
/**
 * [CLASS/FUNCTION INDEX of SCRIPT]
 *
 * Hint: use extdeveval to insert/update function index above.
 */

require_once(PATH_tslib.'class.tslib_pibase.php');

/**
 * Replacer function for deprecated mysql_escape_string()
 *
 * @param $unescaped_string
 * @return string
 */
function mysql_escape_string_replace($unescaped_string) {
    /** @noinspection PhpDeprecationInspection */
    return mysql_escape_string($unescaped_string);
}


/**
 * Plugin 'Featured View' for the 'gk_eisview' extension.
 *
 * @author        Gerhard Kollinger <gerhard@kollinger.it>
 * @package       TYPO3
 * @subpackage    tx_gkeisview
 */
class tx_gkeisview_pi2 extends tslib_pibase {
    var $prefixId = 'tx_gkeisview_pi2'; // Same as class name
    var $scriptRelPath = 'pi2/class.tx_gkeisview_pi2.php'; // Path to this script relative to the extension dir.
    var $extKey = 'gk_eisview'; // The extension key.
    var $pi_checkCHash = TRUE;
    var $templateCode = "";
    private $artist_list_pid_music;
    private $artist_list_pid_discourse;
    const MYSQL_DEBUG = FALSE;
    const MY_IP       = '84.115.153.134';
    public $mysqli;
    public $artist_marker_array;
    public $tpl_artist;

    private static function silentDebug($info = NULL, $mixedOutputVar = 'no_value', $dieAfter = NULL, $htmlCommented = TRUE) {
        if($_SERVER['REMOTE_ADDR'] == self::MY_IP) {
            if($mixedOutputVar != 'no_value') {
                $output = is_array($mixedOutputVar) ? print_r($mixedOutputVar, TRUE) : $mixedOutputVar;
                $output = is_string($output) ? $output : var_export($output, TRUE);
                if($htmlCommented) {
                    echo '<!--'.$info.': '.$output.'-->'."\n";
                } else {
                    echo $info.': '.$output.'<br />'."\n";
                }
                if($dieAfter) {
                    die();
                }
            }
        }

        return;
    }

    /**
     * The main method of the PlugIn
     *
     * @param    string        $content: The PlugIn content
     * @param    array         $conf   : The PlugIn configuration
     * @return    The content that is displayed on the website
     */
    function main($content, $conf) {
        $this->pi_initPIflexForm();
        $this->conf = $conf;
        $this->pi_setPiVarDefaults();
        $this->pi_loadLL();

        // Template Code
        $langKey            = $GLOBALS['TSFE']->sys_language_uid == 0 ? "DE" : "EN";
        $templateFile       = $this->getTemplateName($langKey);
        $this->templateCode = $this->cObj->fileResource($templateFile);

        $this->connectDB();
        $content = $this->getfeaturedArtists();

        return $this->pi_wrapInBaseClass($content);
    }

    function connectDB() {
        $db_params = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['gk_eisview']);

        if(empty($db_params["artist_list_pid_music"]) || empty($db_params["artist_list_pid_discourse"])) {
            die("Bitte Artist-Liste-Musik PID und Artist-Liste-Diskurs PID im Extension Manager eintragen!");
        }
        $this->artist_list_pid_music     = $db_params["artist_list_pid_music"];
        $this->artist_list_pid_discourse = $db_params["artist_list_pid_discourse"];

        $this->mysqli = new mysqli('localhost', $db_params["user"], $db_params["pass"], $db_params["database"]);
        $this->mysqli->query("SET NAMES 'utf8'");

        /*
           * Use this instead of $connect_error if you need to ensure
           * compatibility with PHP versions prior to 5.2.9 and 5.3.0.
           */
        if(mysqli_connect_error() && self::MYSQL_DEBUG) {
            die('Connect Error ('.mysqli_connect_errno().') '.mysqli_connect_error());
        }
    }

    function getfeaturedArtists() {
        $tpl_main         = $this->cObj->getSubpart($this->templateCode, '###FEATURED_VIEW###');
        $this->tpl_artist = $this->cObj->getSubpart($tpl_main, '###ARTIST###');
        $subparts         = array();

        $artist_quantity      = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'quantity');
        $artist_category      = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'category');
        $artist_subcategory   = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'subcategory');
        $artist_year          = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'year');
        $artist_eventlocation = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'eventlocation');
        $daily_featured_date  = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'dailyfeatureddate');
        $daily_featured_sort  = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'dailyfeaturedsort');

        switch($artist_category) {
            case "all":
            case "":
                $artist_category_query = "view_event_appearance.cat_type LIKE '%' and ";
                break;
            default:
                $artist_category_query = "view_event_appearance.cat_type LIKE '%".$artist_category."%' and ";
        }

        switch($artist_subcategory) {
            case "all":
            case "":
                $artist_subcategory_query = "view_event_appearance.cat_type2 LIKE '%' and ";
                break;
            default:
                $artist_subcategory_query = "view_event_appearance.cat_type2 LIKE '%".$artist_subcategory."%' and ";
        }

        switch($artist_year) {
            case "all":
            case "":
                $artist_year_query = "view_event_appearance.event_year LIKE '%' and ";
                break;
            default:
                $artist_year_query = "view_event_appearance.event_year LIKE '%".$artist_year."%' and ";
        }

        switch($artist_eventlocation) {
            case "all":
            case "":
                $artist_eventlocation_query = "view_event_appearance.location_name LIKE '%' and ";
                break;
            default:
                $artist_eventlocation_query = "view_event_appearance.location_name LIKE '%".mysql_escape_string_replace($artist_eventlocation)."%' and ";
        }


        switch($daily_featured_date) {
            case "all":
            case "":
                $daily_featured_date_query = "view_event_appearance.date_name LIKE '%' ";
                $order_by                  = "order by rand() ";
                break;
            default:
                $daily_featured_date_query = "view_event_appearance.date_name LIKE '%".$daily_featured_date."%' ";

                if($daily_featured_sort == "yes") {
                    $order_by = "order by rand() ";
                } else {
                    $order_by = "and view_event_appearance.daily_feature > 0 order by view_event_appearance.daily_feature desc ";
                }
        }


        $query = "select distinct(view_event_appearance.artist_id) from view_event_appearance
		join view_artist on view_event_appearance.artist_id = view_artist.artist_id 
		where ".$artist_category_query.$artist_subcategory_query.$artist_year_query.$artist_eventlocation_query.$daily_featured_date_query.$order_by."limit ".$artist_quantity;

        $result_array1 = $this->getQueryResultArray($query);

        $result_array = array();
        foreach($result_array1 as $artist) {
            $artist_id = $artist["artist_id"];

            $query = "select * from view_artist_light where artist_id = '".$artist_id."'";

            $artist_array = $this->getQueryResultArray($query);

            array_push($result_array, $artist_array[0]);
        }

        $subparts["###ARTIST###"] = "";
        foreach($result_array as $artist_array) {
            $this->artist_marker_array = $this->getArtistMarker($artist_array, "view_artist_light");
            $artist_subpart_array      = $this->getArtistSubparts($artist_array);

            $subparts["###ARTIST###"] .= $this->cObj->substituteMarkerArrayCached($this->tpl_artist, $this->artist_marker_array, $artist_subpart_array);
        }

        return $this->cObj->substituteMarkerArrayCached($tpl_main, array(), $subparts);
    }

    private function getQueryResultArray($query) {
        self::silentDebug("Query", $query);
        if(! $query) {
            return FALSE;
        }

        $results = $this->mysqli->query($query);

        if($this->mysqli->error != "" && self::MYSQL_DEBUG) {
            die("Mysql Error: ".$this->mysqli->error."<br><br>"."Betroffener Query: ".$query);
        }

        $result_array = array();
        while($result = $results->fetch_assoc()) {
            array_push($result_array, $result);
        }
        $results->close();

        return $result_array;
    }

    function getArtistMarker($artist_array, $table = "") {
        $artist_marker_array                = array();
        $artist_marker_array["###table###"] = $table;

        foreach($artist_array as $key => $value) {
            if(empty($value) && $value != "0" || $value == "<br>") {
                $value = $this->conf["featured-view_zero-value"];

                if($key == "title_en") {
                    $value = $input_array["title"];
                } elseif($key == "sub_title_en") {
                    $value = $input_array["sub_title"];
                }
            }

            $artist_marker_array["###view_artist_".$key."###"] = $value;

            if($key == "date_date") {
                $artist_marker_array["###de_datum_kurz###"] = $this->getFormattedDate($value);
                $artist_marker_array["###de_datum_lang###"] = $this->getFormattedDate($value, FALSE);
                $artist_marker_array["###en_datum_kurz###"] = $this->getFormattedDate($value, TRUE, "en");
                $artist_marker_array["###en_datum_lang###"] = $this->getFormattedDate($value, FALSE, "en");
            }
        }

        // Damit die richtige url entsteht und nur 1 cache eintrag geschrieben wird
        $this->prefixId = preg_replace("#2#", "1", $this->prefixId);

        $artist_list_pid = $artist_array["cat_type"] == "art" ? $this->artist_list_pid_music : $this->artist_list_pid_discourse;

        $addurlParameters = array();
        if($artist_array["artist_cat_type"] == "discourse") {
            $addurlParameters['guest'] = $artist_array["url_shortcode"];
        } else {
            if(isset($artist_array["artist_cat_type"])) {
                $addurlParameters['artist'] = $artist_array["url_shortcode"];
            } else {
                if($artist_array["cat_type"] == "discourse") {
                    $addurlParameters['guest'] = $artist_array["url_shortcode"];
                } else {
                    $addurlParameters['artist'] = $artist_array["url_shortcode"];
                }
            }
        }

        $link                                    = $this->pi_linkTP_keepPIvars_url($addurlParameters, TRUE, FALSE, $artist_list_pid);
        $artist_marker_array["###artist_url###"] = $link;

        $this->prefixId = preg_replace("#1#", "2", $this->prefixId);

        $artist_marker_array["###markers###"] = print_r($artist_marker_array, TRUE);


        return $artist_marker_array;
    }

    function getArtistSubparts($artist_array) {
        $artist_subpart_array = array();

        foreach($artist_array as $key => $value) {
            if(empty($value) && $value != "0" || $value == "<br>") {
                $artist_subpart_array["###view_artist_".$key."_subpart###"] = "";
            } else {
                $tpl_artist_subpart = $this->cObj->getSubpart($this->tpl_artist, "###view_artist_".$key."_subpart###");

                $artist_subpart_array["###view_artist_".$key."_subpart####"] = $this->cObj->substituteMarkerArrayCached($tpl_artist_subpart, $this->artist_marker_array, array());
            }
        }

        return $artist_subpart_array;
    }

    function getFormattedDate($date_date_from_db, $short = TRUE, $lang = "de") {
        $date_array = explode("-", $date_date_from_db);

        if(count($date_array) == 3) {
            $timestamp = mktime(0, 0, 0, $date_array[1], $date_array[2], $date_array[0]);
        } else {
            return;
        }

        /*
               if($lang == "de")
               {
                   setlocale(LC_TIME, "de_DE");

                   if($short)
                   {
                       $format = "%a. %d %b";
                   }
                   else
                   {
                       $format = "%A, %d %b";
                   }
               }
               else
               {
                   setlocale(LC_TIME, "en_US");
               }

               return strftime($format, $timestamp);
        */

        if($short) {
            $format = "D. d M";
        } else {
            $format = "l, d M";
        }

        $date = date($format, $timestamp);

        if($lang == "de") {
            $de_names = array("Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag", "Mo", "Di", "Mi", "Do", "Fr", "Sa", "So", "Jan", "Feb", "Mar", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez", "Montag",);

            $en_names = array("#Monday#", "#Tuesday#", "#Wednesday#", "#Thursday#", "#Friday#", "#Saturday#", "#Sunday#", "#Mon#", "#Tue#", "#Wed#", "#Thu#", "#Fri#", "#Sat#", "#Sun#", "#Jan#", "#Feb#", "#Mar#", "#Apr#", "#May#", "#Jun#", "#Jul#", "#Aug#", "#Sep#", "#Oct#", "#Nov#", "#Dec#", "#Motag#",);

            $date = preg_replace($en_names, $de_names, $date);
        }

        return $date;
    }

    /**
     * Get multilanguage template
     *
     * @param    integer        $language: Language
     * @return    string        $t_name: Template
     **/
    function getTemplateName($language) {
        $artist_category = $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'category');

        if($artist_category == "discourse") {
            $t_type = "-discourse";
        } else {
            $t_type = "";
        }


        $t_name            = $this->conf["template_folder_featured-view"].$language.$this->conf["template_name_featured-view".$t_type];
        $standard_template = $this->conf["template_folder_featured-view"]."DE".$this->conf["template_name_featured-view".$t_type];

        if(file_exists($t_name))
            return ($t_name); else if(file_exists($standard_template))
            return ($standard_template); else die ("<p align=center>"."Template: <b>".$t_name."</b> nicht gefunden!</p>");
    }

    function __destruct() {
        $this->mysqli->close();
    }
}


if(defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/gk_eisview/pi2/class.tx_gkeisview_pi2.php']) {
    include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/gk_eisview/pi2/class.tx_gkeisview_pi2.php']);
}

?>